package com.luoran.system.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.luoran.common.core.utils.PrimaryKeyIdUtils;
import com.luoran.system.utils.CellDataDemoHeadDataListenerProcess;
import io.minio.MinioClient;

import io.minio.PutObjectArgs;

import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.luoran.common.core.constant.UserConstants;
import com.luoran.common.core.utils.SecurityUtils;
import com.luoran.common.core.utils.poi.ExcelUtil;
import com.luoran.common.core.web.controller.BaseController;
import com.luoran.common.core.web.domain.AjaxResult;
import com.luoran.common.core.web.page.TableDataInfo;
import com.luoran.common.log.annotation.Log;
import com.luoran.common.log.enums.BusinessType;
import com.luoran.common.security.annotation.PreAuthorize;
import com.luoran.system.api.domain.SysRole;
import com.luoran.system.service.ISysRoleService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 角色信息
 *
 * @author guohailong
 */
@RestController
@RequestMapping("/role")
public class SysRoleController extends BaseController {
    @Autowired
    private ISysRoleService roleService;

    @PreAuthorize(hasPermi = "system:role:list")
    @GetMapping("/list")
    public TableDataInfo list(SysRole role) {
        startPage();
        List<SysRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize(hasPermi = "system:role:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysRole role) throws IOException {
        List<SysRole> list = roleService.selectRoleList(role);
        ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
        util.exportExcel(response, list, "角色数据");
    }


    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize(hasPermi = "system:role:query")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId) {
        return AjaxResult.success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @PreAuthorize(hasPermi = "system:role:add")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysRole role) {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setRoleId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
        role.setCreateBy(SecurityUtils.getUsername());
        return toAjax(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRole(role));
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        return toAjax(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @PreAuthorize(hasPermi = "system:role:remove")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public AjaxResult remove(@PathVariable Long[] roleIds) {
        return toAjax(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize(hasPermi = "system:role:query")
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        return AjaxResult.success(roleService.selectRoleAll());
    }

    private static String bucketName = "2111a";
    private static String accessKey = "c4nOCx7ceoAulhLJ";
    private static String secretKey = "aBXqOvsm3lajcfEGOL434pCYVIi3Vp7D";

    @RequestMapping("/addPic")
    public String addPic(MultipartFile file) {
        MinioClient minioClient = MinioClient.builder().endpoint("http://127.0.0.1:9000").credentials(accessKey, secretKey).build();
        String filename = UUID.randomUUID() + file.getOriginalFilename();
        try {
            minioClient.putObject(PutObjectArgs.builder().object(filename)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType()).bucket(bucketName)
                    .build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "http://127.0.0.1:9000/" + bucketName + "/" + filename;

    }

    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        List<SysRole> list = roleService.list();
        System.out.println(list);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SysRole.class).sheet("模板").doWrite(list);
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize(hasPermi = "system:role:imports")
    @PostMapping("/imports")
    public Map<String, Object> imports(MultipartFile file) {
        HashMap<String, Object> hashMap = new HashMap<>();
        try {
            EasyExcel.read(file.getInputStream(), SysRole.class, new CellDataDemoHeadDataListenerProcess(roleService)).sheet().doRead();
            hashMap.put("msg", "成功");
        } catch (IOException e) {
            e.printStackTrace();
            hashMap.put("msg", "失败");
        }
        return hashMap;
    }

    @GetMapping("/getZxt")
    public AjaxResult getZxt(SysRole sysRole) {
        List<Map<String, String>> list = roleService.getZxt(sysRole);
        System.out.println("--------------------------------" + list);
        return AjaxResult.success(list);
    }


    @RequestMapping("/gettype")
    public AjaxResult gettype() {
        List<SysRole> list = roleService.getlist();
        return AjaxResult.success(list);
    }

    @GetMapping("/getZzt")
    public AjaxResult getZzt(SysRole sysRole) {
        List<Map<String, String>> list = roleService.getZzt(sysRole);
        System.out.println("--------------------------------" + list);
        return AjaxResult.success(list);
    }

    @RequestMapping("/getBing")
    public AjaxResult getBing(@RequestBody SysRole sysRole) {
        List<Map<String, String>> list = roleService.getBing(sysRole);
        System.out.println("--------------------------------" + list);
        return AjaxResult.success(list);
    }
}
